var myOrder = angular.module("myOrderApp", ["scService"]);
myOrder.controller("myOrderController", function($scope, $rootScope, $q, $http, scCodeService, $location, $stateParams, commonService, jsonToStr,pubFun) {
    var appserver = 'http://' + window.location.host + '/appserver/static/wechat-ht/index.html#';
    $scope.loadingToastHide();
    //webSocket
    var userId = localStorage.getItem("userId");
    var pushTimeout='';
    var webSocket = new WebSocket("ws://" + window.location.host + "/appserver/static/websocket/" + userId);
    webSocket.onerror = function(event) {
        
    };
    webSocket.onopen = function(event) {
        
    };
    webSocket.onmessage = function(event) {
        
        var websocketdata = JSON.parse(event.data);
        var websocketdata_data = JSON.parse(websocketdata.data);
        $scope.loadingToastHide();
        //
        if (websocketdata.action == "1001") { //预约成功推送
            reservationSn = websocketdata_data.reservationSn;
            //alert("websocket chargeSn:"+chargeSn);
            
            localStorage.setItem("reservationSn", reservationSn);
            window.location.href = mainConfig.hostUrl + "index.html?#/appointing/" + reservationSn;
        } else if (websocketdata.action == "1002") { //开启充电成功推送
            if(websocketdata_data.actionType=="1" || websocketdata_data.actionType==1){
                chargeSn = websocketdata_data.chargeSn;
                //alert("websocket chargeSn:"+chargeSn);
                
                localStorage.setItem("chargeSn", chargeSn);
                clearInterval(pushTimeout);
                mainConfig.isNotPushFlag=false;
                $rootScope.showWeird = false;
                window.location.href = mainConfig.hostUrl + "index.html?#/charging/"+chargeSn;
            }
        } else if (websocketdata.action == "1003") { //结束充电成功推送
            var orderNo = websocketdata_data.orderNo;
            localStorage.setItem("orderNo", orderNo);
            //alert("websocket orderNo:"+orderNo);
            
            $scope.openCharge = "false";
            localStorage.setItem("openCharge", $scope.openCharge);
            clearInterval(pushTimeout);
            mainConfig.isNotPushFlag=false;
            $rootScope.showWeird = false;
            window.location.href = mainConfig.hostUrl + "index.html?#/orderPay/" + orderNo;
        }

    };
    $scope.processing = {
        chargeList: [],
        reservationList: []
        /*chargeList: [{
            "orderNo": '',
            "createTime": "2016-07-12 18:23:55",
            "status": "正在充电",
            "statusColor": "0",
            "type": "1",
            "btn": "取消预约",
            "link": "link",
            "address": "成都市高新区天府大道中段吉泰路88"
        }],
        reservationList: [{
            "type": "0",
            "orderNo": '',
            "createTime": "2016-07-16 16:43:32",
            "status": "预约成功",
            "statusColor": "1",
            "btn": "结束充电",
            "link": "link",
            "address": "成都市高新区天府大道中段吉泰路88"
        }]*/
    };
    $scope.pendingList = [];
    $scope.overList = [];

    $scope.hasPendingOrder = false;
    $scope.hasOverOrder = false;
    $scope.hasOngoingOperation = false;
    // 获取正在进行中的业务
    /*$rootScope.getOngoingOperation = function() {
        var deferred = $q.defer();
        var userCard = localStorage.getItem("cardNo");
        var postData = {
            userCard: userCard

        };
        scCodeService.getOngoingOperation(postData).then(function(data) {
            //alert(JSON.stringify(data));
            if (data.code == 200) {
                deferred.resolve();
                if (globalFun.isEmptyObj(data.data) == false) {
                    angular.forEach(data.data.chargeList, function(value, index) {
                        if (value.status == "1") {
                            value.status = "正在充电";
                            value.type = "2";
                            
                            $scope.processing.chargeList.push(value);
                        }
                    });
                    angular.forEach(data.data.reservationList, function(value, index) {
                        if (value.status == "1") {
                            value.status = "预约成功";
                            value.type = "1";
                            
                            $scope.processing.reservationList.push(value);
                        }
                    });
                } else {
                    $scope.hasOngoingOperation = false;
                    // $scope.showNoneOrder=true;
                }

            }
        });
        return deferred.promise;
    };*/

    //进行新数据组装到老数据上
    $scope.dataToOrderList = function(obj) {
            angular.forEach(obj, function(value, index) {
                var link = appserver + '/orderDetail/' + value.orderNo;
                value.link = link;
                if (value.status < 2) {
                    $scope.hasPendingOrder = true;
                    $scope.pendingList.push(value);
                } else {
                    $scope.hasOverOrder = true;

                    $scope.overList.push(value);
                }
            });
        }
        //定义获取订单参数
    $scope.orderList = [];
    $scope.pageNo = 1; //页码
    $scope.isPush = true; //是否需要加载数据    
    //根据用户id获取订单列表
    $scope.getOrderList = function() {
        var deferred = $q.defer();
        var userId = localStorage.getItem("userId");
        var postData = {
            'userId': userId, //userId
            'pageNo': $scope.pageNo
        }
        scCodeService.getOrderList(postData).then(function(data) {
            if (data.code == "200") {
                deferred.resolve(data);
                if (globalFun.isEmptyObj(data.data) == false) {
                    
                    //将新数据组装到之前数据上进行显示
                    $scope.dataToOrderList(data.data);
                    //$scope.orderList=data.data;
                    if (data.data.length < 20) {
                        $scope.isPush = false;
                    }
                } else {
                    $scope.isPush = false;
                    $scope.hasPendingOrder = false;
                    $scope.hasOverOrder = false;
                }

            }
        })
        return deferred.promise;
    }
    //上拉加载数据
    window.onscroll = function() {
        // 
        var wh = window.pageYOffset + window.screen.height;
        var dh = document.body.scrollHeight;
        // 
        if (wh >= dh && $scope.isPush) {
            $scope.pageNo++;
            $scope.getOrderList();
        }
    };
    // 进入页面执行的方法
    $q.all([pubFun.getOngoingOperation(), $scope.getOrderList()]).then(function(data) {
        
        // var path = $location.path();
        // $scope.tabOrder(path);        
        $scope.hasOngoingOperation = data[0].hasOngoingOperation; 
        $scope.showNoneOrder = $scope.hasOngoingOperation == false ? true : false; //是否存在订单
        $scope.processing = data[0];
        var newDate = new Date();
        angular.forEach($scope.processing.reservationList, function(value, index,array){
            newDate.setTime(array[index].startTime);
            var M = (newDate.getMonth()+1 < 10 ? '0'+(newDate.getMonth()+1) : newDate.getMonth()+1);
            $scope.processing.reservationList[index].startTime=newDate.getFullYear()+"-"+M+"-"+newDate.getDate()+" "+newDate.getHours()+":"+newDate.getMinutes()+":"+newDate.getSeconds();
        });
        angular.forEach($scope.processing.chargeList, function(value, index,array){
            newDate.setTime(array[index].startTime);
            var M = (newDate.getMonth()+1 < 10 ? '0'+(newDate.getMonth()+1) : newDate.getMonth()+1);
            $scope.processing.chargeList[index].startTimestr=newDate.getFullYear()+"-"+M+"-"+newDate.getDate()+" "+newDate.getHours()+":"+newDate.getMinutes()+":"+newDate.getSeconds();
        });
    });
    // tab判断有无相应的订单
    $scope.activeStyle = 0;
    $scope.showState1 = true;
    $scope.tabOrder = function(data) {
        $scope.activeStyle = data-1;
        switch (data) {
            case 1:
            // case "/myOrder/processing":
                $scope.showNoneOrder = $scope.hasOngoingOperation == false ? true : false;
                break;
            case 2:
            // case "/myOrder/pending":
                $scope.showNoneOrder = $scope.hasPendingOrder == false ? true : false;
                break;
            case 3:
            // case "/myOrder/over":
                $scope.showNoneOrder = $scope.hasOverOrder == false ? true : false;
                break;

        };
        for(var i = 1;i< 4;i++){
             var showState = "showState"+i
            if(data==i){
                $scope[showState] = true;
                continue; 
            }
            $scope[showState]=false;
        }
    };
    //取消预约或结束充电
    $scope.process = function(data) {
        mainConfig.isNotPushFlag=true;
        if (data.type == 1) {
            $scope.weirdConfirmSet({
                title: "",
                content: "确定要取消预约？",
                buttonAux: '点错了',
                buttonMain: '确定',
                icon:"excl",
                data: { type: "1", reservationSn: data.reservationSn } //type: "1"，取消预约 "2"，结束充电
            });
        } else if (data.type == 2) {
            $scope.weirdConfirmSet({
                title: "",
                content: "确定要结束充电？",
                buttonAux: '点错了',
                buttonMain: '确定',
                icon:"excl",
                data: { type: "2", chargeSn: data.chargeSn, }
            });
        };
    };
    //点击进入预约界面
    $rootScope.goToAppointing=function (qrCode,reservationSn) {
        var postData = {
            qrCode: qrCode
        }
        scCodeService.getChargerDetailByQrCode(postData).then(function(data) {
            
            if (data.code == "200") {
                if (data.data) {
                    $scope.chargerDetail = data.data;
                    
                    //组装桩类型数据
                    if ($scope.chargerDetail.chargerType == "1") {
                        $scope.chargerDetailType = "直流 快充"
                    } else if ($scope.chargerDetail.chargerType == "2") {
                        $scope.chargerDetailType = "交流220V 慢充"
                    }
                    pubFun.getRate($scope.chargerDetail.chargerId).then(function(data){
                        $scope.mainRate = data;
                        localStorage.setItem("chargerDetail", JSON.stringify($scope.chargerDetail));
                        localStorage.setItem("mainRate", JSON.stringify($scope.mainRate));
                        pubFun.getStationDetail($scope.chargerDetail.stationId).then(function (data) {
                            localStorage.setItem("latitude",data.latitude);
                            localStorage.setItem("longitude",data.longitude);
                            window.location.href = mainConfig.hostUrl+'index.html#/appointing/'+reservationSn;
                        });
                    });
                }
            } else {
                Popup.notice('获取桩信息失败', 3000, function() {
                    
                });
            }
        })
    }
    //点击进入充电界面
    $rootScope.goToCharging=function (qrCode,chargeSn,startTime,startTimestr) {
        var postData = {
            qrCode: qrCode
        }
        scCodeService.getChargerDetailByQrCode(postData).then(function(data) {
            
            if (data.code == "200") {
                if (data.data) {
                    $scope.chargerDetail = data.data;
                    
                    var temp = new Date();
                    var SMS = Date.parse(temp);
                    localStorage.setItem("SMS", startTime);
                    
                    localStorage.setItem("startTime", startTimestr);
                    //判断充电开启状态
                    $scope.openCharge = "true";
                    localStorage.setItem("openCharge", $scope.openCharge);
                    localStorage.setItem("chargerDetail", JSON.stringify($scope.chargerDetail));
                    //chargerId and plugNo
                    localStorage.setItem("chargerId", $scope.chargerDetail.chargerId);
                    localStorage.setItem("plugNo", $scope.chargerDetail.plugNoList[0].portNo);
                    pubFun.getRate($scope.chargerDetail.chargerId).then(function(data){
                        localStorage.setItem("rate", data.chargerRate);
                        window.location.href = mainConfig.hostUrl+'index.html#/charging/'+chargeSn;
                    });
                    
                }
            } else {
                Popup.notice('获取桩信息失败', 3000, function() {
                    
                });
            }
        })
        
    }
});
